﻿using DropBoxClient.Entities;
using DropBoxClient.Framework;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;

namespace DropBoxClient.Operations
{
    internal class GetThumbnailsOperation
    {
        private static readonly string Url = "https://api-content.dropbox.com/1/thumbnails/{0}/{1}";
        private static readonly string MethodType = StringConstants.GetMethodType;

        private string _accessToken;

        internal string Root { get; set; }
        internal string Path { get; set; }

        internal GetThumbnailsOperation(string accessToken)
        {
            _accessToken = accessToken;
        }

        internal ImageContent Execute()
        {
            string url = string.Format(Url, Root, Path);
            var imageContent = new ImageContent();
            var request = WebRequest.Create(url);
            request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + _accessToken);
            request.Method = MethodType;
            using (var response = request.GetResponse())
            {
                imageContent.Content = new byte[response.ContentLength];
                response.GetResponseStream().Read(imageContent.Content, 0, (int)response.ContentLength);
                string json = response.Headers.Get("x-dropbox-metadata");
                var jsonBuffer = Encoding.UTF8.GetBytes(json);
                var jsonStream = new MemoryStream(jsonBuffer);
                var serializer = new DataContractJsonSerializer(typeof(FileMeta));
                imageContent.Meta = (FileMeta)serializer.ReadObject(jsonStream);
            }
            var imageConverter = new ImageConverter();
            imageContent.Image = (Image)imageConverter.ConvertFrom(imageContent.Content);
            return imageContent;
        }
    }
}
